package com.ljy.my_study.leetcode.按权重随机选择;

import java.util.TreeMap;

/**
 * @author lijunying
 * @date 2021/8/30 9:38
 */
public class Solution {

    public static void main(String[] args) {
        int[] w=new int[]{1,3};
        Solution solution=new Solution(w);
        System.out.println(solution.pickIndex());
        System.out.println(solution.pickIndex());
        System.out.println(solution.pickIndex());
        System.out.println(solution.pickIndex());
        System.out.println(solution.pickIndex());
        System.out.println(solution.pickIndex());
        System.out.println(solution.pickIndex());
        System.out.println(solution.pickIndex());
        System.out.println(solution.pickIndex());
        System.out.println(solution.pickIndex());
        System.out.println(solution.pickIndex());
        System.out.println(solution.pickIndex());
    }

    int sum=0;
    private TreeMap<Double,Integer> map=new TreeMap<>();

    public Solution(int[] w) {
        int count=0;
        for(int i=0;i<w.length;i++){
            count+=w[i];
            map.put((double)count,i);
        }
        this.sum=count;
    }

    public int pickIndex() {
        double key=Math.random()*sum;
        key=map.ceilingKey(key);
        return map.get(key);
    }
}
